/*
 * Copyright 2008-2010 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public License Version 3
 * The license can be read in its entirety in the LICENSE.txt file accompanying this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of Libra.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see: http://www.gnu.org/licenses
 */

package net.cachapa.libra.dailyburn;

import java.util.Vector;

import android.content.Context;
import android.util.Log;

import net.cachapa.libra.R;
import net.cachapa.libra.data.Database;
import net.cachapa.libra.data.Value;

public class Synchronizer {
	public static String importEntries(Context context) {
		DailyBurnApi dailyBurn = DailyBurnApi.getInstance(context);
		// Get the values from the server
		String entriesXml = dailyBurn.get(DailyBurnApi.BODY_LOG_ENTRIES);
		if (entriesXml == null) {
			return context.getString(R.string.connection_failed);
		}
		Log.d("Synchronizer", "Got xml from DailyBurn");
		Vector<Value> values = XmlParser.parseBodyLogEntries(entriesXml);
		Database database = Database.getInstance(context);
		int inserted = 0;
		for (Value value : values) {
			// TODO If the value already exists, ask the user which value to keep
			if (database.insertValue(value)) {
				database.setSynched(value);
				inserted++;
				Log.d("Synchronizer", "Inserted " + value);
			}
		}
		String result;
		switch (inserted) {
		case 0:
			result = context.getString(R.string.import_complete_nothing); 
			break;
		case 1:
			result = context.getString(R.string.import_complete_one); 
			break;
		default:
			result = context.getString(R.string.import_complete_many);
			break;
		}
		return String.format(result, inserted);
	}
	
	public static int uploadEntries(Context context) {
		// Get all of the unsynchronized values from the local database
		Database database = Database.getInstance(context);
		Vector<Value> values = database.getUnsynchedValues();
		// And post them, one by one
		DailyBurnApi dailyBurn = DailyBurnApi.getInstance(context);
		int uploaded = 0;
		for (Value value : values) {
			try {
				dailyBurn.postValue(value);
				database.setSynched(value);
				uploaded++;
			} catch (Exception e) {
				e.printStackTrace();
				uploaded = -1;
			}				
		}
		return uploaded;
	}
}
